package com.lovo.service.impl;

import com.lovo.dao.StudentBeanDAO;
import com.lovo.model.*;
import com.lovo.model.DTO.ClassDTO;
import com.lovo.model.DTO.CourseDTO;
import com.lovo.model.DTO.StudentDTO;
import com.lovo.model.vo.PageVO;
import com.lovo.service.StudentService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentBeanDAO studentBeanDAO;

    @Override
    public PageVO findAll(Integer page, Integer size) {
//        System.out.println(page+"***"+size);
        Page<StudentBean> pageObj = studentBeanDAO.findAll(PageRequest.of(page - 1, size));
        List StudentDTOlist = new ArrayList();
        for (StudentBean s : pageObj.getContent()) {
//            System.out.println(s);
            StudentDTO studentDTO = new StudentDTO(s.getStudentId(), s.getName(), s.getGender());
            if (s.getClassBean() != null) {
                ClassDTO classDTO = new ClassDTO(s.getClassBean().getClassId(), s.getClassBean().getName());
                studentDTO.setClassDTO(classDTO);
            }
            List<CourseBean> courseBeanList = s.getCourseBeanList();
            if (courseBeanList != null) {
                for (CourseBean c : courseBeanList) {
                    CourseDTO courseDTO = new CourseDTO(c.getCourseId(), c.getName());
                    studentDTO.getCourseDTOList().add(courseDTO);
                }
            }
            StudentDTOlist.add(studentDTO);
        }
        return new PageVO(pageObj.getNumber() + 1, pageObj.getSize(), pageObj.getTotalElements(), StudentDTOlist);
    }

    @Override
    public StudentDTO findByStudentId(Integer studentId) {
        StudentBean studentBean = studentBeanDAO.findByStudentId(studentId);
        StudentDTO studentDTO = new StudentDTO(studentBean.getStudentId(), studentBean.getName(), studentBean.getGender());
        return studentDTO;
    }

    @Override
    public void addStudentBean(StudentDTO studentDTO) {
        StudentBean studentBean = new StudentBean(studentDTO.getName(), studentDTO.getGender());
        studentBeanDAO.save(studentBean);
    }

    @Override
    public void update(Integer id, StudentDTO studentDTO) {
        StudentBean studentBean = new StudentBean(studentDTO.getName(), studentDTO.getGender());
        studentBean.setStudentId(id);
        studentBeanDAO.save(studentBean);
    }

    @Override
    public void del(Integer id) {
        StudentBean studentBean = new StudentBean();
        studentBean.setStudentId(id);
        studentBeanDAO.delete(studentBean);
    }
}
